import {computed, getCurrentInstance, reactive, ref, toRefs} from "vue";
import {DictData} from "@/hooks/useTranslateDictCode/useTranslateDictCode";
import {roleList} from "@/views/system/user/hooks/useSearch";
import {deleteUser, getUserById, insertUser, updateUser, UpdateUserForm, UserForm} from "@/api/system/user";
import {currentDept} from "@/views/system/user/hooks/useDeptTree";
import {ElMessage, ElMessageBox} from "element-plus";
import {Role} from "@/views/system/role/hooks/useTable";
import useTable from "@/views/system/user/hooks/useTable";
import useButtonDisabled from "@/hooks/useButtonDisabled/useButtonDisabled";
import {uploadFile} from "@/api";
export default  function useForm() {
    const currentInstance = getCurrentInstance();
    const {getUserDataList} = useTable()
    const {btnDisabled,clearBtnDisabled} = useButtonDisabled()
    const userFormReactive = reactive<{userForm: UserForm}>({
        userForm:{
            username:'',
            password:'',
            phone:'',
            nickname:'',
            dataStatus:1,
            avatar:'',
            roleIds:[]
        }
    })
    const rules = reactive({
        username:[
            {required:true,message:'请填写用户名',trigger:'blur'},
            {min:4,max:20,message:'用户名必须在4-20位字符',trigger:'blur'}
        ],
        password:[
            {required:true,message:'请填写密码',trigger:'blur'},
            {min:6,max:16,message: '密码必须是6-16位字符',trigger:'blur'}
        ],
        password2:[
            {min:6,max:16,message: '密码必须是6-16位字符',trigger:'blur'}
        ],
        phone:[
            {required:true,message:'请填写手机号',trigger:'blur'},
            {min:11,max:11,message:'请填写手机号',trigger:'blur'}
        ],
        nickname:[
            {required:true,message:'请填写用户昵称',trigger:'blur'},
            {min:0,max:20,message: "用户昵称不能超过20个字符",trigger:'blur'}
        ]
    })
    const visible = ref(false)
    const isEdit = ref(false)
    function addUser() {
        isEdit.value =false
        if(!currentDept.value){
            ElMessage.error("请选择部门创建用户")
            return
        }
        userFormReactive.userForm.deptId = currentDept.value?.id
        visible.value = true
    }
    function editUser(id: number) {
        getUserById(id).then(res=>{
            userFormReactive.userForm = res.data
            userFormReactive.userForm.roleIds = res.data.roles.map((d: Role)=>d.id)
            userFormReactive.userForm.password = ''
            userFormReactive.userForm.deptId = res.data.dept?.id
            isEdit.value = true
            visible.value = true
        })
    }
    async function delUser(id: number) {
        await  ElMessageBox.confirm("确定要删除当前用户？" ,"提示",{
            type:"warning"
        })
        deleteUser(id).then(()=>{
            ElMessage.success("删除成功")
            getUserDataList()
        })
    }
    function submit(e: MouseEvent) {
        //eslint-disable-next-line
        (currentInstance?.refs.userFormRef as any).validate((valid: boolean)=>{
            if (!valid){
                return
            }
            btnDisabled(e)
            if (isEdit.value){
                updateUser(userFormReactive.userForm as UpdateUserForm).then(()=>{
                    ElMessage.success("修改成功")
                    visible.value = false
                    getUserDataList()
                    clearBtnDisabled(e)
                }).catch(()=>{
                    clearBtnDisabled(e)
                })
            }else {
                insertUser(userFormReactive.userForm).then(()=>{
                    ElMessage.success("添加成功")
                    visible.value = false
                    getUserDataList()
                    clearBtnDisabled(e)
                }).catch(()=>{
                    clearBtnDisabled(e)
                })
            }
        })
    }
    function cutDown(cutImage: {file: File}) {
        uploadFile([cutImage.file]).then(res=>{
            if(res.data.length === 1){
                userFormReactive.userForm.avatar = res.data[0].path
                ElMessage.success("头像上传成功")
            }
        })
    }
    function resetUserForm() {
        userFormReactive.userForm = {
            username:'',
            password:'',
            phone:'',
            nickname:'',
            dataStatus:1,
            avatar:'',
            roleIds:[]
        }
    }
    const roleDictOptions = computed<DictData[]>(()=>{
        return roleList.value.map(d=>{
            return {
                label:d.roleDesc,
                value:d.id
            }
        })
    })
    return {
        roleDictOptions,
        isEdit,
        rules,
        visible,
        submit,
        delUser,
        addUser,
        editUser,
        ...toRefs(userFormReactive),
            cutDown,
        resetUserForm
    }
}
